package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.entity.Region;
import com.yuelao.yuelao_backend.mapper.RegionMapper;
import com.yuelao.yuelao_backend.service.RegionService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 地区Service实现类
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    @Override
    public List<Region> getProvinces() {
        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Region::getLevel, 1) // 省级
               .orderByAsc(Region::getCode);
        return list(wrapper);
    }

    @Override
    public List<Region> getCities(String provinceCode) {
        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Region::getParentId, provinceCode)
               .eq(Region::getLevel, 2) // 市级
               .orderByAsc(Region::getCode);
        return list(wrapper);
    }

    @Override
    public List<Region> getDistricts(String cityCode) {
        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Region::getParentId, cityCode)
               .eq(Region::getLevel, 3) // 区县级
               .orderByAsc(Region::getCode);
        return list(wrapper);
    }

    @Override
    public Map<String, Object> getAllRegions() {
        // 一次性查询所有地区数据，避免 N+1 查询问题
        List<Region> allRegions = list(new LambdaQueryWrapper<Region>().orderByAsc(Region::getCode));
        
        // 按 parentId 分组，便于快速查找子节点
        Map<String, List<Region>> childrenMap = allRegions.stream()
                .filter(r -> r.getParentId() != null)
                .collect(Collectors.groupingBy(Region::getParentId));
        
        // 获取所有省份（level=1）
        List<Map<String, Object>> provinceList = allRegions.stream()
                .filter(r -> r.getLevel() == 1)
                .map(province -> buildRegionNode(province, childrenMap))
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("regions", provinceList);
        return result;
    }
    
    /**
     * 递归构建地区节点（支持任意层级）
     */
    private Map<String, Object> buildRegionNode(Region region, Map<String, List<Region>> childrenMap) {
        Map<String, Object> node = new HashMap<>();
        node.put("code", region.getCode());
        node.put("name", region.getName());
        node.put("level", region.getLevel());
        
        // 查找子节点
        List<Region> children = childrenMap.get(region.getCode());
        if (children != null && !children.isEmpty()) {
            List<Map<String, Object>> childNodes = children.stream()
                    .map(child -> buildRegionNode(child, childrenMap))
                    .collect(Collectors.toList());
            node.put("children", childNodes);
        }
        
        return node;
    }
}

